package basic

import (
	"path/filepath"
	"time"

	"gitee.com/Luna-CY/Golang-Project-Template/entry/http/request"
	"gitee.com/Luna-CY/Golang-Project-Template/entry/http/response"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context/contextutil"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/i18n"
	"github.com/gin-gonic/gin"
)

type UploadRequest struct {
	Scenario string `form:"scenario" validate:"required" binding:"required"` // 场景
}

type UploadResponse struct {
	Id  string `json:"id" validate:"required"`  // 文件ID
	Url string `json:"url" validate:"required"` // 文件URL
}

// Upload 上传文件
// @tags basic
// @summary 上传文件
// @accept multipart/form-data
// @param param query UploadRequest true "request query"
// @param file formData file true "file"
// @success 200 {object} response.Response{data=UploadResponse{}} "successful. click to expand response structure"
// @router /basic/upload [post]
func (cls *Basic) Upload(c *gin.Context) (response.Code, any, errors.I18nError) {
	var body = UploadRequest{}
	if err := request.ShouldBindQuery(c, &body); nil != err {
		return response.InvalidParams, nil, errors.NewI18n(i18n.CommonIdInvalidRequest, err.Relation(errors.ErrorInvalidRequest("SHGWHB_IC.B_IC.U_AD.210303", "参数错误")))
	}

	var ctx = contextutil.NewContextWithGin(c)

	fh, err2 := c.FormFile("file")
	if nil != err2 {
		return response.InvalidParams, nil, errors.NewI18n(i18n.CommonIdInvalidRequest, errors.New(errors.ErrorTypeInvalidRequest, "SHGWHB_IC.B_IC.U_AD.291300", err2.Error()))
	}

	f, err3 := fh.Open()
	if nil != err3 {
		return response.InvalidParams, nil, errors.NewI18n(i18n.CommonIdInvalidRequest, errors.New(errors.ErrorTypeInvalidRequest, "SHGWHB_IC.B_IC.U_AD.351903", err3.Error()))
	}

	defer f.Close()

	var path = filepath.Join(body.Scenario, time.Now().Format("2006_01_02"), fh.Filename)
	object, err := cls.storage.PutObject(ctx, path, time.Now().Add(1*time.Hour).Unix(), false, f)
	if nil != err {
		return response.ServerInternalError, nil, errors.NewI18n(i18n.CommonIdServerInternalError, err.Relation(errors.ErrorServerInternalError("SHGWHB_IC.B_IC.U_AD.482341", "上传文件失败")))
	}

	url, err := cls.storage.GetObjectAccessedUrl(ctx, object, time.Minute*15)
	if nil != err {
		return response.ServerInternalError, nil, errors.NewI18n(i18n.CommonIdServerInternalError, err.Relation(errors.ErrorServerInternalError("SHGWHB_IC.B_IC.U_AD.591415", "获取文件URL失败")))
	}

	return response.Ok, UploadResponse{Id: object.Id, Url: url}, nil
}
